/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.spestimator.files.fasta.merge;

import com.compomics.dbtoolkit.toolkit.Concatenate;
import com.compomics.spestimator.analysis.FastaParameters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;

/**
 *
 * @author Kenneth
 */
public class FastaMerger {

    private static final String DBTOOLKIT_CLASS_NAME = "com.compomics.dbtoolkit.toolkit.Concatenate";
    private static final Logger LOGGER = Logger.getLogger(FastaMerger.class);

    public static void mergeFastaFiles(File fasta1, File fasta2, File outputFile) {
        // --input1 <input1_file_name> [--input2 <input2_file_name>] <output_file_name>
        LOGGER.info("Merging fastafiles using dbToolkit : ");
        ArrayList<String> arguments = new ArrayList<>();
        arguments.add("--input1");
        arguments.add(fasta1.getAbsolutePath());
        arguments.add("--input2");
        arguments.add(fasta2.getAbsolutePath());
        arguments.add(outputFile.getAbsolutePath());
        System.out.println(arguments.toString().replace(",", " "));
        String[] argumentsAsArray = new String[arguments.size()];
        Concatenate.main(arguments.toArray(argumentsAsArray));
        LOGGER.info("Merged fastafiles");
    }

    public static void mergeAndRename(HashMap<String, String> speciesMap, File outputFile) {
        if (outputFile.exists()) {
            outputFile.delete();
        }
        for (String aTaxID : speciesMap.keySet()) {
            try {
                rewriteAccessions(new File(speciesMap.get(aTaxID)), aTaxID, outputFile);
            } catch (IOException ex) {
                LOGGER.error(ex);
            }
        }
    }

    private static void rewriteAccessions(File fasta, String speciesName, File outputFile) throws IOException {
        RandomAccessFile file = new RandomAccessFile(fasta, "rw");
        String strLine;
        int accessionCounter = 0;
        PrintWriter out = new PrintWriter(new FileOutputStream(outputFile, true));
        while (file.getFilePointer() < file.length()) {
            strLine = file.readLine();
            if (strLine.startsWith(">")) {
                accessionCounter++;
                //replace the header with a simplified sequence
                strLine = ">spes|" + speciesName + "SPESNR" + accessionCounter + "|" + accessionCounter;
            }
            out.println(strLine);
            out.flush();
        }
       FastaParameters.putAccessionCountForSpecies(speciesName, accessionCounter);

    }

    public static void main(String args[]) {
        try {
            File fasta1 = new File(FastaMerger.class.getResource("/fasta1.FASTA").toURI());
            File fasta2 = new File(FastaMerger.class.getResource("/fasta2.FASTA").toURI());
            File output = new File(FastaMerger.class.getResource("/output.FASTA").toURI());
            mergeFastaFiles(fasta1, fasta2, output);
            //read this file
            try (InputStream in = new FileInputStream(output);
                    BufferedReader reader =
                    new BufferedReader(new InputStreamReader(in))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException x) {
                System.err.println(x);
            }
        } catch (URISyntaxException ex) {
            LOGGER.error(ex);
        }

    }
}
